<template>
  <div 
    class="node" 
    :class="[nodeTypeClass, { 'selected': isSelected, 'dragging': isDragging }]"
    :style="nodeStyle"
    @mousedown="handleNodeMouseDown"
  >
    <div class="node-header">
      {{ getNodeTypeName }}
    </div>
    <div class="node-body">
      <!-- 输入端口 -->
      <div class="node-inputs">
        <div 
          v-for="(input, index) in node.inputs" 
          :key="index"
          class="node-port node-input"
          :class="input.type"
          @mouseup="handlePortMouseUp('input', index)"
        >
        <div class="port-dot"></div>
          <span class="port-label">{{ input.name }}</span>
        </div>
      </div>
      
      <!-- 输出端口 -->
      <div class="node-outputs">
        <div 
          v-for="(output, index) in node.outputs" 
          :key="index"
          class="node-port node-output"
          :class="output.type"
          @mousedown="handlePortMouseDown('output', index, $event)"
        >
          <span class="port-label">{{ output.name }}</span>
          <div class="port-dot"></div>
        </div>
      </div>
    </div>
    
    <!-- 连线预览 -->
    <svg v-if="isDraggingConnection" class="connection-preview" :style="connectionPreviewStyle">
      <path :d="connectionPath" stroke="#666" stroke-width="2" fill="none"/>
    </svg>
  </div>
</template>

<script>
export default {
  name: 'Node',
  props: {
    node: {
      type: Object,
      required: true
    },
    isSelected: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isDragging: false,
      dragOffsetX: 0,
      dragOffsetY: 0,
      hasMoved: false,
      isDraggingConnection: false,
      connectionStartX: 0,
      connectionStartY: 0,
      connectionEndX: 0,
      connectionEndY: 0,
      sourcePortIndex: -1
    };
  },
  computed: {
    connectionPreviewStyle() {
      return {
        position: 'fixed',
        left: '0',
        top: '0',
        width: '100%',
        height: '100%',
        pointerEvents: 'none',
        zIndex: 1000
      };
    },
    connectionPath() {
      const dx = this.connectionEndX - this.connectionStartX;
      const dy = this.connectionEndY - this.connectionStartY;
      const bezierX = Math.abs(dx) * 0.5;
      return `M ${this.connectionStartX} ${this.connectionStartY} 
              C ${this.connectionStartX + bezierX} ${this.connectionStartY},
                ${this.connectionEndX - bezierX} ${this.connectionEndY},
                ${this.connectionEndX} ${this.connectionEndY}`;
    },
    nodeTypeClass() {
      return {
        'node-flow': this.node.type === 'flow',
        'node-procedure': this.node.type === 'procedure',
        'node-product': this.node.type === 'product'
      };
    },
    nodeStyle() {
      return {
        left: `${this.node.x}px`,
        top: `${this.node.y}px`,
        width: `${this.node.width}px`,
        height: `${this.node.height}px`,
        'border-left': this.node.type === 'flow' ? '4px solid #48bb78' : 
                      this.node.type === 'procedure' ? '4px solid #4299e1' : 
                      '4px solid #9f7aea'
      };
    },
    getNodeTypeName() {
      return this.node.type === 'product' ? '产品节点' : 
             this.node.type === 'flow' ? '流程节点' : '过程节点';
    }
  },
  methods: {
    handlePortMouseDown(portType, index, event) {
      if (portType === 'output') {
        this.isDraggingConnection = true;
        this.sourcePortIndex = index;
        
        const portElement = event.target.closest('.node-port');
        const portRect = portElement.getBoundingClientRect();
        
        this.connectionStartX = portRect.right;
        this.connectionStartY = portRect.top + portRect.height / 2;
        this.connectionEndX = this.connectionStartX;
        this.connectionEndY = this.connectionStartY;
        
        // 设置拖拽源节点
        this.$parent.draggingSourceNode = this.node;
        
        document.addEventListener('mousemove', this.handleConnectionDrag);
        document.addEventListener('mouseup', this.handleConnectionDrop);
        
        event.stopPropagation();
      }
    },
    
    handleConnectionDrag(event) {
      if (this.isDraggingConnection) {
        this.connectionEndX = event.clientX;
        this.connectionEndY = event.clientY;
      }
    },
    
    handleConnectionDrop(event) {
      if (this.isDraggingConnection) {
        const targetPort = event.target.closest('.node-port');
        if (targetPort && targetPort.classList.contains('node-input')) {
          const index = Array.from(targetPort.parentElement.children).indexOf(targetPort);
          this.$emit('connection-created', {
            source: this.$parent.draggingSourceNode.id,
            sourcePortIndex: this.sourcePortIndex,
            target: this.node.id,
            targetPortIndex: index
          });
        }
      }
      this.isDraggingConnection = false;
      document.removeEventListener('mousemove', this.handleConnectionDrag);
      document.removeEventListener('mouseup', this.handleConnectionDrop);
    },
    
    handlePortMouseUp(portType, index) {
      if (this.isDraggingConnection && portType === 'input') {
        // 获取目标节点的DOM元素
        const targetPort = event.target.closest('.node-port');
        if (targetPort) {
          this.$emit('connection-created', {
            source: this.$parent.draggingSourceNode.id,
            sourcePortIndex: this.sourcePortIndex,
            target: this.node.id,
            targetPortIndex: index
          });
        }
      }
    },
    
    handleNodeMouseDown(e) {
      if (e.target.classList.contains('node-header') || 
          e.target.classList.contains('node-body')) {
        if (!e.target.closest('.node-port')) {
          this.isDragging = e.target.classList.contains('node-header');
          this.hasMoved = false;
          this.dragOffsetX = e.clientX - this.node.x;
          this.dragOffsetY = e.clientY - this.node.y;
          if (this.isSelected) {
            this.$emit('select', null);
          }
          document.addEventListener('mousemove', this.handleDrag);
          document.addEventListener('mouseup', this.stopDrag);
        }
      }
    },
    handleDrag(e) {
      if (!this.isDragging) return;
      this.hasMoved = true;
      this.$emit('update:position', {
        id: this.node.id,
        position: {
          x: e.clientX - this.dragOffsetX,
          y: e.clientY - this.dragOffsetY
        }
      });
    },
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.handleDrag);
      document.removeEventListener('mouseup', this.stopDrag);
      
      if (!this.hasMoved) {
        this.$emit('select', this.node);
      } else if (this.isSelected) {
        this.$emit('select', this.node);
      }
      this.hasMoved = false;
    }
  }
};
</script>

<style>
@import '../assets/styles/node.css';
</style>